package per.mapt.spring;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by mapeif on 2017/3/14.
 */
public class SessionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse res = (HttpServletResponse)response;
        HttpSession session= req.getSession();
        String user = (String) session.getAttribute("userid");
        if(user == null){
            String uri = req.getRequestURI();
            System.out.println(uri);
            if(uri.length()==req.getContextPath().length()+1&& uri.startsWith(req.getContextPath())){
                chain.doFilter(request,response);
                return;
            }
            if(uri.contains("on.jsp")||uri.contains("login")){
               chain.doFilter(request,response);
                System.out .println(456);
            }else{
                res.sendRedirect( req.getContextPath()+"/");

            }
            System.out.flush();
            return ;
        }
        chain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
